#include "MLBenchmark.h"
#include "ErrorHandling.h"

#include <opencv/ml.h>

#include <QDir>


using namespace std;
using namespace cv;


Scheme MLBenchmark::scheme;


bool ReadFileList(const FileNode& node, FileList& fl, QFileInfo benchmarkInfo);


void MLBenchmark::LoadPatterns(const std::string& path)
{
    if(!scheme.Load(path+"/"+"benchmark.yml"))
	{
		ES_Error("Не удалось загрузить бенчмарк");
	}
}


bool MLBenchmark::Load(const std::string& filename)
{
	FileStorage storage(filename, FileStorage::READ);
	if(!storage.isOpened() )
	{
		return false;
	}
    scheme.Check(&storage);

    QFileInfo benchmarkInfo = QFileInfo(QString::fromStdString(filename));
    this->filename = benchmarkInfo.absoluteFilePath().toStdString();
	FileNode top = storage.getFirstTopLevelNode();

    bool dataFlag = ReadFileList(top["data_sets"], data, benchmarkInfo);
    bool algoFlag = ReadFileList(top["algorithms"], algorithms, benchmarkInfo);

	storage.release();
    return dataFlag && algoFlag;
}


bool ReadFileList(const FileNode& node, FileList& fl, QFileInfo benchmarkInfo)
{
    string relativePath;
    node["directory"] >> relativePath;

    QDir benchmarkDir(benchmarkInfo.path());
    bool isValidDir = benchmarkDir.cd(QString::fromStdString(relativePath));
    if(!isValidDir)
    {
        return false;
    }

    fl.directory = benchmarkDir.absolutePath().toStdString();
    fl.name.clear();
    FileNode config_files = node["config_files"];
    for(FileNodeIterator iter = config_files.begin();iter!=config_files.end();iter++)
    {
        fl.name.push_back(*iter);
    }
    return true;
}
